package service

import (
	"api/app/ctl/models"
	"api/config"
	"api/libs/errs"
	"gitee.com/dreamwood/ez"
	"os"
	"os/exec"
	"path"
	"strings"
)

func StartHost(id int) {
	curd := models.NewStarterCrud()

	starter, e := curd.Find(id)
	if errs.Try(e) {
		return
	}
	err := os.Chdir(starter.Path)
	defer func() {
		os.Chdir(config.GetCore().GetRoot())
	}()
	if errs.Try(err) {
		return
	}
	params := strings.Fields(starter.Params)
	cmd := exec.Command(starter.Starter, params...)
	err = cmd.Start()

	if errs.Try(err) {
		return
	}
	starter.Pid = cmd.Process.Pid
	starter.StartAt = ez.Now()
	starter.Save()
}

func CheckStarter4Start(id int) *os.Process {
	curd := models.NewStarterCrud()
	starter, e := curd.Find(id)
	if errs.Try(e) {
		return nil
	}
	process, e := os.FindProcess(starter.Pid)
	if errs.Try(e) {
		return nil
	}
	return process
}

func StopHost(id int) {
	curd := models.NewStarterCrud()
	starter, e := curd.Find(id)
	if errs.Try(e) {
		return
	}
	process := CheckStarter4Start(id)
	if process != nil {
		ez.PrintError(process.Kill())
	}
	starter.Pid = 0
	starter.StartAt = nil
	starter.Save()
}

func CreateStarterFromAppHost(appHostId int) {
	hostCrud := models.NewAppHostCrud()
	host, e := hostCrud.Find(appHostId)
	if errs.Try(e) {
		return
	}
	fullPath := strings.ReplaceAll(host.Starter, string(os.PathSeparator), "/")
	fullPath = path.Clean(fullPath)
	root, _ := path.Split(fullPath)
	if root == "." {
		root, _ = os.Getwd()
	}
	starter := models.Starter{
		Path:    root,
		Starter: fullPath,
	}
	starter.Save()
}
func AutoStartStarter() {
	crud := models.NewStarterCrud()
	//找到所有自启动的项目
	finds, e := crud.FindBy(ez.M{"isAuto": true}, nil, 0, 0)
	ez.PrintError(e)
	for _, find := range finds {
		StartHost(find.Id)
	}
}
